//
//  ZZUserAccountViewModel.swift
//  SinaWeibo
//
//  Created by QUAN on 15/11/11.
//  Copyright © 2015年 QUAN. All rights reserved.
//

import UIKit
import AFNetworking

class ZZUserAccountViewModel: NSObject {

    
    var account: ZZUserAccount?
    
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var token: String? {
        return account?.access_token
    }
    
    var userName: String? {
        return account?.name
    }
    
    var headURl: NSURL? {
        return NSURL(string: account?.avatar_large ?? "")
    }
    
    override init() {
        account = ZZUserAccount.loadAccount()
    }
    
    //获取token值
    func loadAccessToken(code: String, finished: (error: NSError?) -> ()) {
        
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code","code": code, "redirect_uri": redirect_uri]
        
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finished(error: nil)
                return
            }
            
            //字典转模型
            let account = ZZUserAccount(dict: result!)
            
            self.loadUserInfo(account, finised: finished)

            
        }
    }
    
    //获取用户信息
    private func loadUserInfo(account: ZZUserAccount, finised: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token": account.access_token!, "uid" : account.uid!]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String: AnyObject] {
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                
                print(account)
                
                account.saveAccount()
                
                finised(error: nil)
            }
            }) { (_, error) -> Void in
                finised(error: error)
                print(error)
        }
    }
}
